package com.rock.code.bigdata.bigdatainterface.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rock.code.hdfs.HdfsAPP;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;


/**
 * @author zhouhao
 * @description 工具类
 * @date 2018/11/7 9:57
 * @Version 1.0
 */
public class MyUtil {

    /**
     * get请求
     *
     * @param url
     * @return 请求结果
     */
    public static JSONObject doGet(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        byte[] bytes = EntityUtils.toByteArray(entity);
        String result = new String(bytes, "utf-8");
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }


    /**
     * get请求  返回值json数组
     *
     * @param url
     * @return 请求结果
     */
    public static JSONArray doGetArray(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        byte[] bytes = EntityUtils.toByteArray(entity);
        String result = new String(bytes, "utf-8");
        JSONArray proArray = JSONArray.parseArray(result);
        return proArray;
    }


    /**
     * post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPost(String url, JSONObject json) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        //尝试使用短连接
        post.setProtocolVersion(HttpVersion.HTTP_1_0);
        post.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
        post.setConfig(requestConfig);
        JSONObject response = null;

        StringEntity s = new StringEntity(json.toString());
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");//发送json数据需要设置contentType
        post.setEntity(s);
        HttpResponse res = httpClient.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(res.getEntity());// 返回json格式：
            response = JSONObject.parseObject(result);
        }

        return response;
    }


    /**
     * 追加数据到文件中
     *
     * @param file   文件路径  String类型
     * @param conent 文件内容
     */
    public static void appendData(String file, String conent) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file, true)));
            out.write(conent + "\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取输入时间的时间戳
     *
     * @param beginDate 时间
     * @return
     */
    public static String timeToTimeStamp(String beginDate) {
        String result = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = format.parse(beginDate);
            long timeStamp = date.getTime();
            String tmpTime = String.valueOf(timeStamp);
            result = tmpTime.substring(0, tmpTime.length());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;

    }


    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;

    }


    public static String stampToDate1(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;

    }

    /**
     * 增加删除文件方法
     *
     * @param path
     * @param filename
     */
    public static void delFile(String path, String filename) {
        File file = new File(path + "/" + filename);
        if (file.exists() && file.isFile())
            file.delete();
    }


    /**
     * 日期增加一个月
     *
     * @param s
     * @param n
     * @return
     */
    public static String addMonth(String s, int n) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Calendar cd = Calendar.getInstance();
            cd.setTime(sdf.parse(s));
//            cd.add(Calendar.DATE, n);//增加一天   
            cd.add(Calendar.MONTH, n);//增加一个月   

            return sdf.format(cd.getTime());

        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 日期增加一天
     *
     * @param s
     * @param n
     * @return
     */
    public static String addDay(String s, int n) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Calendar cd = Calendar.getInstance();
            cd.setTime(sdf.parse(s));
            cd.add(Calendar.DATE, n);//增加一天   
//            cd.add(Calendar.MONTH, n);//增加一个月   

            return sdf.format(cd.getTime());

        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 比较两个日期大小
     *
     * @param DATE1
     * @param DATE2
     * @return
     */
    public static int compare_date(String DATE1, String DATE2) {


        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }


    /**
     * 将每天采集的历史数据上传到hdfs目录
     *
     * @param fileClass 文件上传的目录
     * @param year      年份  按年分割数据
     * @param timeDay   日期  格式如：20180201
     */
    public static void putFileToHdfs(String fileClass, String year, String timeDay) throws IOException {
        String filename = "hisData" + timeDay + ".txt";

        String hdfsPath = null;
        hdfsPath = "/user/xxjsb_zk/" + fileClass + "/" + year + "/performance/bnms/original/" + filename;
        String file = "/root/datas/" + filename;

        new HdfsAPP().writeHDFS(file, hdfsPath);
        //加入成功标志以方便脚本监测标志来判断采集是否成功
        MyUtil.delFile("/root/datas/", filename);
        System.out.println(filename + "文件已删除！");


    }

    /**
     * 获取定义月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static String getDateLastDay(int year, int month) {

        Calendar calendar = Calendar.getInstance();
        // 设置时间,当前时间不用设置
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);

        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDate = sdf.format(calendar.getTime());
        return lastDate;
    }

    /**
     * 获取定义时间10天后的日期
     *
     * @param date yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getEndDate(String date) {
        String time = date.split(" ")[0];
        int year = Integer.parseInt(time.split("-")[0]);
        int month = Integer.parseInt(time.split("-")[1]);
        int day = Integer.parseInt(time.split("-")[2]);
        LocalDate localDate = LocalDate.of(year, month, day);
        LocalDate localDate1 = localDate.plus(10, ChronoUnit.DAYS);

        String localDate3 = localDate1.toString() + " " + "00:00:00";

        return localDate3;
    }


    public static void main(String[] args) throws Exception {
        String where = "alarmStatus=2 or alarmStatus=3";
        String ip = "10.90.133.113";
        String startTime = "20161222101008";
        String endTime = "20171222101008";
        String url = "http://" + ip + ":8082/query/mo/AlarmEvent?where=(" + where + " ) and (alarmTime between " + "'" + startTime + "'" + " and " + "'" + endTime + "'" + ")";
        System.out.println(url);

        String urlFormat = url.replace("(", "%28").replace(")", "%29").replace(" ", "%20").replace("'", "%27").replace("=","%3D");
        System.out.println(urlFormat);
    }
}
